package com.white.algebra.listener;

import com.white.algebra.dao.DiscussDao;
import com.white.algebra.dao.impl.DiscussDaoImpl;
import com.white.algebra.domain.Discuss;
import com.white.algebra.utils.JedisPoolUtils;
import redis.clients.jedis.Jedis;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RedisWork implements Runnable {

    //初始化redis数据
    public static void init() throws SQLException {
        Jedis jedis= JedisPoolUtils.getJedis();
        DiscussDao discussDao=new DiscussDaoImpl();
        List<Discuss> list=discussDao.findAllDiscuss();
        Map<String,String> map=new HashMap<>();
        for (Discuss d:list) {
            d.toString();
            map.put(d.getId(),String.valueOf(d.getThumbsUp()));
        }

        jedis.hmset("discuss",map);
        jedis.close();
    }

    //查询所有点赞数据
    public static Map<String, String> findAll(){
        Jedis jedis= JedisPoolUtils.getJedis();
        Map<String,String> map=jedis.hgetAll("discuss");
        return map;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        Jedis jedis= JedisPoolUtils.getJedis();
        Map<String,String> map=jedis.hgetAll("discuss");
        DiscussDao discussDao=new DiscussDaoImpl();
        for(Map.Entry<String, String> entry : map.entrySet()){
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            try {
                discussDao.updateThumbsUp(mapKey,mapValue);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        jedis.close();
        try {
            init();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
